package com.tsingteng.cosfun.ui.found.adapter;

import android.content.Context;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.pili.pldroid.player.IMediaController;
import com.pili.pldroid.player.PLOnInfoListener;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.bean.EventBean;
import com.tsingteng.cosfun.bean.FoundJoinBean;
import com.tsingteng.cosfun.bean.OpusBean;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class FoundVideoListAdapter extends RecyclerView.Adapter {

    String TAG = "foundVideoList";

    public enum FooterState {
        Normal, Loading, TheEnd;
    }

    private Context mContext;
    private FoundViewHolder mFoundViewHolder;
    private Map<String, FoundViewHolder> videoPlayer; //缓存本地播放器
    private List<String> videoIds; //缓存本地播放器
    private List<OpusBean> listVideo;
    private IMediaController.MediaPlayerControl playerControl = null;
    private OnItemClickLisenter onItemClickLisenter = null;
    private OnCanClickListener mOnCanClickListener;
    public static final String EVENT_PAUSE = "EVENT_PAUSE";
    public static final String EVENT_START = "EVENT_START";
    private long pageType = 0;
    public FooterHolder mFooterHolder;

    public FoundVideoListAdapter(Context context, long pageType, List<OpusBean> listResps, OnItemClickLisenter lisenter,OnCanClickListener mOnCanClickListener) {
        this.mContext = context;
        this.mOnCanClickListener =mOnCanClickListener;
        this.pageType = pageType;
        this.listVideo = listResps;
        this.onItemClickLisenter = lisenter;
        videoPlayer = new HashMap<String, FoundViewHolder>();//缓存本地播放器
        videoIds = new ArrayList<>();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        if (viewType == 0) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_found_video_view, parent, false);
            return new FoundViewHolder(view);
        } else {//加载更多
            view = LayoutInflater.from(mContext).inflate(R.layout.listview_footer, parent, false);
            mFooterHolder = new FooterHolder(view);
            return mFooterHolder;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof FoundViewHolder) {
            ((FoundViewHolder) holder).setData(position);
            addPlayer(position, ((FoundViewHolder) holder));
        }
    }

    @Override
    public int getItemCount() {
        if (listVideo == null) {
            return 0;
        }
        return listVideo.size();
    }

    class FoundViewHolder extends RecyclerView.ViewHolder {
        private PLVideoTextureView mFoundVideoPv;
        private ImageView mFoundVideoIv;
        private ImageView mFoundVideoPlayIv;
        private RelativeLayout rootView;
        private TextView mCanJoinTv;
        int currentSelect = 0;

        public FoundViewHolder(View itemView) {
            super(itemView);
            mFoundVideoPv = itemView.findViewById(R.id.found_video_pv);
            mFoundVideoIv = itemView.findViewById(R.id.found_video_iv);
            mFoundVideoPlayIv = itemView.findViewById(R.id.found_video_play_iv);
            rootView = itemView.findViewById(R.id.found_item_view_root_view);
            mCanJoinTv = itemView.findViewById(R.id.can_join_tv);
        }

        @Subscriber(tag = FoundVideoListAdapter.EVENT_PAUSE)
        void playerPause(EventBean eventBean) {
            if (mFoundVideoPv != null && pageType == eventBean.getType()) {
                mFoundVideoPv.pause();
            }
        }


        @Subscriber(tag = FoundVideoListAdapter.EVENT_START)
        void playerStart(EventBean eventBean) {
            if (eventBean.getPosition() == currentSelect && mFoundVideoPv != null && pageType == eventBean.getType()) {
                mFoundVideoPv.setMediaController(iMediaController);
                final OpusBean opusBean = listVideo.get(currentSelect);
                if (!mFoundVideoPv.isPlaying()) {
                    mFoundVideoPv.setVideoPath(opusBean.getVideoUrl());
                    mFoundVideoPv.start();
                }
                mFoundVideoPlayIv.setVisibility(View.INVISIBLE);
            }
        }

        public void setData(int position) {
            currentSelect = position;
            final OpusBean opusBean = listVideo.get(position);
            if (opusBean.getWidth() == 0 || opusBean.getHeight() == 0) {
                mFoundVideoPv.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT);//铺满屏幕
            } else if (opusBean.getWidth() > opusBean.getHeight()) {//宽度大于高度
                mFoundVideoPv.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_FIT_PARENT);//适应屏幕
            } else {
                mFoundVideoPv.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT);//铺满屏幕
            }
            Glide.with(mContext).load(opusBean.getVideoCverUrl()).into(mFoundVideoIv);
            mFoundVideoPv.setCoverView(mFoundVideoIv);
            mFoundVideoPv.setVideoPath(opusBean.getVideoUrl());
            mFoundVideoPv.setMediaController(iMediaController);
            mFoundVideoPv.setLooping(true);
            mFoundVideoPv.setOnInfoListener(mOnInfoListener1);
            mFoundVideoPlayIv.setVisibility(View.INVISIBLE);
            if ("1".equals(opusBean.getIsActivity())){
                mCanJoinTv.setText(mContext.getResources().getString(R.string.can_join));
            }else{
                mCanJoinTv.setText(mContext.getResources().getString(R.string.costar));
            }
            rootView.setOnClickListener(v -> playVideo());

            mFoundVideoPlayIv.setOnClickListener(v -> playVideo());
            mCanJoinTv.setOnClickListener(view -> mOnCanClickListener.showCanClick(opusBean));
        }

        public void playVideo() {
            new Handler().postDelayed(() -> {
                if (mFoundVideoPv != null) {
                    if (mFoundVideoPv.isPlaying()) {
                        mFoundVideoPv.pause();
                        mFoundVideoPlayIv.setVisibility(View.VISIBLE);
                    } else {
                        mFoundVideoPv.setMediaController(iMediaController);
                        mFoundVideoPv.start();
                        mFoundVideoPlayIv.setVisibility(View.INVISIBLE);
                    }

                }
            }, 500);
        }

        private PLOnInfoListener mOnInfoListener1 = new PLOnInfoListener() {
            @Override
            public void onInfo(int what, int extra) {
                Log.i(TAG, "OnInfo, what = " + what + ", extra = " + extra);
                switch (what) {
                    case PLOnInfoListener.MEDIA_INFO_BUFFERING_START://开始缓冲
                        break;
                    case PLOnInfoListener.MEDIA_INFO_BUFFERING_END://停止缓冲
                        break;
                    case PLOnInfoListener.MEDIA_INFO_VIDEO_RENDERING_START://第一帧视频已成功渲染
                        break;
                    case PLOnInfoListener.MEDIA_INFO_AUDIO_RENDERING_START://第一帧音频已成功播放
                        if (onItemClickLisenter != null) {
                            onItemClickLisenter.showPlayProgress(0, playerControl);
                        }
//                        mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 100);
                        break;
                    case PLOnInfoListener.MEDIA_INFO_VIDEO_FRAME_RENDERING:
                        Log.i(TAG, "video frame rendering, ts = " + extra);
                        break;
                    case PLOnInfoListener.MEDIA_INFO_AUDIO_FRAME_RENDERING://音频帧的时间戳
                        Log.i(TAG, "audio frame rendering, ts = " + extra);
                        break;
                    case PLOnInfoListener.MEDIA_INFO_VIDEO_GOP_TIME:
                        Log.i(TAG, "Gop Time: " + extra);
                        break;
                    case PLOnInfoListener.MEDIA_INFO_SWITCHING_SW_DECODE:
                        Log.i(TAG, "Hardware decoding failure, switching software decoding!");
                        break;
                    case PLOnInfoListener.MEDIA_INFO_METADATA:
                        break;
                    case PLOnInfoListener.MEDIA_INFO_VIDEO_BITRATE:
                    case PLOnInfoListener.MEDIA_INFO_VIDEO_FPS:
//                    updateStatInfo();
                        break;
                    case PLOnInfoListener.MEDIA_INFO_CONNECTED:
                        Log.i(TAG, "Connected !");
                        break;
                    case PLOnInfoListener.MEDIA_INFO_LOOP_DONE:// loop 中的一次播放完成
                        break;
                    case PLOnInfoListener.MEDIA_INFO_VIDEO_ROTATION_CHANGED:
                        Log.i(TAG, "Rotation changed: " + extra);
                    default:


                        break;
                }
            }
        };
        private IMediaController iMediaController = new IMediaController() {
            @Override
            public void setMediaPlayer(MediaPlayerControl mediaPlayerControl) {
                playerControl = mediaPlayerControl;
                if (onItemClickLisenter != null) {
                    onItemClickLisenter.showPlayProgress(0, playerControl);
                }
            }

            @Override
            public void show() {

            }

            @Override
            public void show(int i) {

            }

            @Override
            public void hide() {

            }

            @Override
            public boolean isShowing() {
                return false;
            }

            @Override
            public void setEnabled(boolean b) {

            }

            @Override
            public void setAnchorView(View view) {

            }
        };
    }

    private void addPlayer(int position, FoundViewHolder holder) {
        if (videoPlayer == null) {
            videoPlayer = new HashMap<>();
        }
        if (videoIds.size() < 5) {
            videoPlayer.put(position + "", holder);
            videoIds.add(position + "");
        } else {
            String id = videoIds.remove(0);
            if (videoPlayer.get(id + "") != null) {
                videoPlayer.get(id + "").mFoundVideoPv.stopPlayback();
            }
            videoPlayer.remove(id);
            videoPlayer.put(position + "", holder);
            videoIds.add(position + "");
        }

    }

    public class FooterHolder extends RecyclerView.ViewHolder {
        View mLoadingViewstubstub;
        View mEndViewstub;
        public FoundVideoListAdapter.FooterState status = FoundVideoListAdapter.FooterState.Normal;

        public FooterHolder(View itemView) {
            super(itemView);
            mLoadingViewstubstub = itemView.findViewById(R.id.glistview_footer_content_rel);
            mEndViewstub = itemView.findViewById(R.id.glistview_footer_nomore_rel);
        }

        //根据传过来的status控制哪个状态可见
        public void setStatus(FooterState status) {
            this.status = status;
            switch (status) {
                case Normal:
                    setAllGone();
                    break;
                case Loading:
                    setAllGone();
                    mLoadingViewstubstub.setVisibility(View.VISIBLE);
                    break;
                case TheEnd:
                    setAllGone();
                    mEndViewstub.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }

        }

        //全部不可见
        void setAllGone() {
            if (mLoadingViewstubstub != null) {
                mLoadingViewstubstub.setVisibility(View.GONE);
            }
            if (mEndViewstub != null) {
                mEndViewstub.setVisibility(View.GONE);
            }
        }

    }

    public void stopPlay(int position) {
        if (videoPlayer.get(position + "") != null) {
            videoPlayer.get(position + "").mFoundVideoPv.stopPlayback();
        }
        try {
            Set<Map.Entry<String, FoundViewHolder>> set = videoPlayer.entrySet();
            for (Map.Entry<String, FoundViewHolder> me : set) {
                FoundViewHolder value = me.getValue();
                if (value != null) {
                    value.mFoundVideoPv.stopPlayback();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startPlay(int position) {
        if (videoPlayer.get(position + "") != null) {
            final OpusBean opusBean = listVideo.get(position);
            if (!videoPlayer.get(position + "").mFoundVideoPv.isPlaying()) {
                videoPlayer.get(position + "").mFoundVideoPv.setVideoPath(opusBean.getVideoUrl());
                videoPlayer.get(position + "").mFoundVideoPv.start();
                videoPlayer.get(position + "").mFoundVideoPlayIv.setVisibility(View.INVISIBLE);
            }
        }
    }

    public void clearPlayer() {
        if (videoPlayer != null) {
            try {
                Set<Map.Entry<String, FoundViewHolder>> set = videoPlayer.entrySet();
                for (Map.Entry<String, FoundViewHolder> me : set) {
                    FoundViewHolder value = me.getValue();
                    if (value != null) {
                        value.mFoundVideoPv.stopPlayback();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            videoPlayer.clear();
            videoIds.clear();
        }
    }

    public interface OnItemClickLisenter {
        void showPlayProgress(int position, IMediaController.MediaPlayerControl mediaPlayerControl);
    }
    public interface OnCanClickListener{
        void showCanClick(OpusBean opusBean);
    }
}
